const vm = new Vue({
  el: '#app',
  data: {
    todos: [
      {isSelected: false, title: '睡觉'},
      {isSelected: false, title: '吃饭'}
    ],
    title: '',
    cur: '',
    hash:''
  },
  methods: {
    remove(item) {
      this.todos = this.todos.filter(i => i !== item)
    },
    add(e) {
      console.log(this.title)
      this.todos.push({isSelected: false, title: this.title});
      this.title = ''
    },
    doubleLi(item) {
      this.cur = item
    },
    cancel() {
      this.cur = ''
    }
  },
  created() {
    // 如果localstorage中有数据，就用数据，没有就用默认
    this.todos = JSON.parse(localStorage.getItem('vue_data')) || this.todos;

    this.hash = window.location.hash.slice(2) || 'all';

    //监控hash值的变化
    window.addEventListener('hashchange',()=>{
      this.hash = window.location.hash.slice(2);
    },false);
  },
  watch: { // watch默认只监控一层数据的变化
    todos: {
      handler() { // 默认写成函数 相当于默认谢了handler
        // localStorage
        localStorage.setItem('vue_data', JSON.stringify(this.todos))
      },
      deep: true
    }
  },
  computed: {
    filterTodos(){
      if(this.hash === 'all') return this.todos
      if(this.hash === 'finish') return this.todos.filter(item => item.isSelected)
      if(this.hash === 'unfinish') return this.todos.filter(item=> !item.isSelected)
    },
    count() {
      return this.todos.filter(item => !item.isSelected).length
    }
  },
  directives: {
    focusAa(el, bindings) {
      if (bindings.value) {
        el.focus()
      }
    }
  }
})
